package com.walkline.screen;

import java.util.Hashtable;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.walkline.travelassistant.TravelAssistantSDK;
import com.walkline.travelassistant.inf.Direction;

public class RefreshContentsScreen extends PopupScreen
{
	private Thread thread = null;
	private TravelAssistantSDK _travelAssistant;
	private Direction _directionResult = null;

	public RefreshContentsScreen(TravelAssistantSDK travelAssistant, final Hashtable params)
	{
		super(new VerticalFieldManager());

		_travelAssistant = travelAssistant;

		add(new LabelField("Please wait....", Field.FIELD_HCENTER));

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				thread = new Thread(new QueryDirectionRunnable(params));
				thread.start();				
			}
		});
	}

	class QueryDirectionRunnable implements Runnable
	{
		private String mode = "";
		private String region = "";
		private String origin = "";
		private String origin_region = "";
		private String destination = "";
		private String destination_region = "";

		public QueryDirectionRunnable(Hashtable params)
		{
			mode = (String) params.get("mode");
			region = (String) params.get("region");
			origin = (String) params.get("origin");
			origin_region = (String) params.get("origin_region");
			destination = (String) params.get("destination");
			destination_region = (String) params.get("destination_region");
		}

		public void run()
		{
			_directionResult = _travelAssistant.queryDirection(mode, region, origin, origin_region, destination, destination_region);

			Application.getApplication().invokeLater(new Runnable() {public void run() {onClose();}});
		}
	}

	public Direction getDirectionResult() {return _directionResult;}

	public boolean onClose()
	{
		if (thread != null)
		{
			try {
				thread.interrupt();
				thread = null;
			} catch (Exception e) {}
		}

		try {
			UiApplication.getUiApplication().popScreen(this);	
		} catch (Exception e) {}

		return true;
	}

	protected boolean keyChar(char key, int status, int time)
	{
		if (key == Characters.ESCAPE)
		{
			onClose();

			return true;
		}

		return super.keyChar(key, status, time);
	}
} 